package main

import "fmt"

/*
* Author: JacksonCoder
* CreateTime: 2024/11/30
 */

/*
*
延迟 调用
*/
func Defer() {
	defer func() {
		println("this is one")
	}()
	defer func() {
		println("this is two")
	}()
}

func DeferClosure() {
	i := 0
	defer func() {
		println(i)
	}()
	i = 1
}

func DeferClosureV1() {
	i := 0
	defer func(val int) {
		println(val)
	}(i)
	i = 1
}

/*
*
defer 用于释放资源
*/
//func Query() {
//	db, _ := sql.Open("", "")
//	defer db.Close()
//	db.Query("SELECT")
//}

func DeferReturn() int {
	a := 0
	defer func() {
		a = 1
	}()
	return a
}

// 返回值会被修改
func DeferReturnV1() (a int) {
	a = 0
	defer func() {
		a = 1
	}()
	return a
}

func DeferClosureLoopV1() {
	//var j int
	for i := 0; i < 10; i++ {
		//j = i
		defer func() {
			fmt.Printf("i 的地址是 : %p  值是 %d \n", &i, i)
			//println(i)
		}()
	}
}

func DeferClosureLoopV2() {
	for i := 0; i < 10; i++ {
		defer func(val int) {
			fmt.Printf("val的地址是 : %p  值是 %d \n", &val, val)
			//println(val)
		}(i)
	}
}

func DeferClosureLoopV3() {
	for i := 0; i < 10; i++ {
		j := i
		defer func() {
			fmt.Printf("j的地址是 : %p  值是 %d \n", &j, j)
			//println(j)
		}()
	}
}

func main() {
	//Defer()
	//DeferClosure()
	//DeferClosureV1()
	//println(DeferReturn())
	//println(DeferReturnV1())

	DeferClosureLoopV1()
	DeferClosureLoopV2()
	DeferClosureLoopV3()

}
